/**
 * 
 */
package com.ws.framework.dao.impl;

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.ws.framework.dao.CodeDao;
import com.ws.framework.model.Code;
import com.ws.framework.model.Page;

/**
 * <p>
 * </p>
 *
 * @author WSH
 */
@Repository
public class CodeDaoImpl implements CodeDao {

	@Autowired
	JdbcTemplate jdbcTemplate;
	
	private static final String insertCodeSql = "INSERT INTO t_code_info(app_id, code_name, code_desc, create_time) VALUES (?, ?, ? ,?);";
	
	private static final String queryForPageBaseSql = "select id, app_id AS appId, code_name AS codeName, code_desc AS codeDesc, create_time AS createTime FROM t_code_info WHERE 1 = 1 ";

	private static final String deleteByIdSql = "DELETE FROM t_code_info WHERE id = ?;";
	
	private static final String queryForBeanSql = "select id, app_id AS appId, code_name AS codeName, code_desc AS codeDesc,code_context As codeContext, create_time AS createTime FROM t_code_info WHERE id = ?;";

	private static final String queryForBeanByCondeNameSql = "select id, app_id AS appId, code_name AS codeName, code_desc AS codeDesc,code_context As codeContext, create_time AS createTime FROM t_code_info WHERE code_name = ?;";
	
	private static final String updateContextSql = "UPDATE t_code_info SET code_context = ? WHERE id = ?;";
	
	private static final String updateSql = "UPDATE t_code_info SET code_name = ?,code_desc = ? WHERE id = ?;";
	
	@Override
	public Page<Code> select4Paget(Page<Code> page) {
		String sql = queryForPageBaseSql + page.getSomeLikeOtherEqCondition("code_name");
		return page.get(sql, jdbcTemplate, Code.class);
	}
	
	@Override
	public int insert(Code code) {
		return jdbcTemplate.update(insertCodeSql, code.getAppId(), code.getCodeName(), code.getCodeDesc(), new Timestamp(System.currentTimeMillis()));
	}
	
	@Override
	public int update(Code code) {
		return jdbcTemplate.update(updateSql, code.getCodeName(), code.getCodeDesc(), code.getId());
	}

	@Override
	public void delete(long id) {
		jdbcTemplate.update(deleteByIdSql, id);
	}

	@Override
	public Code selectById(long id) {
		return jdbcTemplate.queryForObject(queryForBeanSql, new Object[]{id}, new BeanPropertyRowMapper<Code>(Code.class));
	}
	
	@Override
	public Code selectByCodeName(String codeName) {
		return jdbcTemplate.queryForObject(queryForBeanByCondeNameSql, new Object[]{codeName}, new BeanPropertyRowMapper<Code>(Code.class));
	}

	@Override
	public int updateContextById(String context, long id) {
		return jdbcTemplate.update(updateContextSql, context, id);
	}

}
